<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useItemsStore } from '../stores/items'
import { useInventoryStore } from '../stores/inventory'
import { useStatisticsStore } from '../stores/statistics'
import { useUserStore } from '../stores/user'
import { usePermissionStore } from '../stores/permission'
import { messagesApi } from '../utils/apiService'
import { Cpu, OfficeBuilding, Food, ShoppingBag, More, Bell, Box, UserFilled } from '@element-plus/icons-vue'

const router = useRouter()
const itemsStore = useItemsStore()
const inventoryStore = useInventoryStore()
const statisticsStore = useStatisticsStore()
const userStore = useUserStore()
const permissionStore = usePermissionStore()

const loading = ref(true)
const isDarkMode = ref(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)
const allMessages = ref([]) // 存储所有消息数据

// 用户数据
const user = computed(() => {
  const storeUser = userStore.getUser; // userStore.getUser returns state.user
  if (storeUser) {
    return {
      // 模仿 SettingsView.vue 的逻辑：优先 username，其次 nickname，然后 name
      name: storeUser.username || storeUser.nickname || storeUser.name || '未知用户',
      avatar: storeUser.avatar || '' // 保留头像逻辑
    };
  }
  return {
    name: '未知用户',
    avatar: ''
  };
})

// 获取统计数据
const totalItems = computed(() => itemsStore.getTotalItemsCount)
const lowStockItems = computed(() => inventoryStore.getLowStockItems)
const expiringItems = computed(() => inventoryStore.getExpiringItems)
const recentPurchases = computed(() => statisticsStore.getRecentPurchases)
const itemsByLocation = computed(() => statisticsStore.getItemCountByLocation)

// 计算需要注意的总数
const totalAlertsCount = computed(() => lowStockItems.value.length + expiringItems.value.length)

// 统计卡片数据
const statCards = computed(() => [
  { 
    id: 'total', 
    title: '总物品数量', 
    count: totalItems.value, 
    icon: 'Document', 
    colorClass: 'blue', 
    route: '/dashboard/items',
    active: totalItems.value > 0
  },
  { 
    id: 'low-stock', 
    title: '库存不足物品', 
    count: lowStockItems.value.length, 
    icon: 'Warning', 
    colorClass: 'orange', 
    route: '/dashboard/inventory',
    active: lowStockItems.value.length > 0
  },
  { 
    id: 'expiring', 
    title: '即将过期物品', 
    count: expiringItems.value.length, 
    icon: 'Time', 
    colorClass: 'red', 
    route: '/dashboard/inventory',
    active: expiringItems.value.length > 0
  },
  { 
    id: 'locations', 
    title: '物品存储位置', 
    count: Object.keys(itemsByLocation.value).length, 
    icon: 'DataLine', 
    colorClass: 'green', 
    route: '/dashboard/statistics',
    active: Object.keys(itemsByLocation.value).length > 0
  }
])

// 添加快速操作数据
const quickActions = [
  { id: 1, label: '添加物品', icon: 'Plus', route: '/dashboard/items', query: { openAddDialog: 'true' }, colorClass: 'bg-green' },
  { id: 2, label: '扫描条码', icon: 'Sunny', route: '/scan', colorClass: 'bg-blue' },
  { id: 3, label: '转移物品', icon: 'Right', route: '/items/transfer', colorClass: 'bg-orange' },
  { id: 4, label: '批量导入', icon: 'Upload', route: '/import', colorClass: 'bg-purple' },
  { id: 5, label: '导出数据', icon: 'Download', route: '/export', colorClass: 'bg-indigo' },
  { id: 6, label: '打印标签', icon: 'Printer', route: '/print', colorClass: 'bg-cyan' }
]

// 位置数据
const locationData = computed(() => {
  const locations = Object.keys(itemsByLocation.value)
  const colors = ['#007AFF', '#5AC8FA', '#34C759', '#FF9500', '#FF3B30', '#AF52DE']
  
  return locations.map((name, index) => ({
    name,
    count: itemsByLocation.value[name],
    color: colors[index % colors.length]
  }))
})

// 最近活动数据 - 直接从allMessages计算得出
const recentActivities = computed(() => {
  const activities = allMessages.value
    .filter(msg => {
      // 检查消息是否有有效ID
      if (!msg.id) {
        return false;
      }
      
      // 检查messageType和subType字段，兼容不同命名格式
      const msgType = msg.messageType || msg.message_type;
      const subType = msg.subType || msg.sub_type;
      
      // 只显示活动类型消息
      const isActivityMessage =
        msgType === 'activity' &&
        ['create', 'update', 'delete', 'move', 'login', 'logout', 'permission'].includes(subType);

      return isActivityMessage;
    })
    .map(item => ({
      id: item.id,
      title: item.title,
      content: item.content,
      actionType: item.subType || item.sub_type,
      time: item.createTime || item.create_time,
      userName: item.userName || item.user_name || (item.sourceUserId ? '用户' : '系统'),
      locationName: item.locationName || item.location_name || '',
      userId: item.userId || item.user_id,
      locationId: item.locationId || item.location_id,
      itemId: item.itemId || item.item_id,
      itemName: item.itemName || item.item_name || '',
      priority: item.priority,
      read: (item.isRead === 1) || (item.is_read === 1) || (item.isRead === true) || (item.is_read === true)
    }))
    .sort((a, b) => new Date(b.time) - new Date(a.time));

  return activities;
})

// 最近操作数据 - 从recentActivities转换
const recentOperations = computed(() => {
  if (recentActivities.value && recentActivities.value.length > 0) {
    return recentActivities.value.slice(0, 5).map(activity => {
      const timeAgo = formatTimeAgo(activity.time)
      
      // 根据活动类型生成统一格式的操作记录
      let operation = {
        id: activity.id,
        username: activity.userName || '未知',
    avatar: '',
        action: '',
        item: activity.itemName || '',
        time: activity.time,
        timeAgo: timeAgo
      }
      
      // 根据活动类型设置具体操作信息
      switch (activity.actionType) {
        case 'create':
          operation.action = '添加了物品'
          break
        case 'update':
          operation.action = '更新了物品'
          if (activity.content && activity.content.includes('更新了库存')) {
            operation.action = '更新了库存'
            // 尝试从内容中提取数量信息
            const match = activity.content.match(/从\s*(\d+)\s*更新为\s*(\d+)/)
            if (match) {
              operation.oldQuantity = parseInt(match[1])
              operation.newQuantity = parseInt(match[2])
            }
          }
          break
        case 'delete':
          operation.action = '删除了物品'
          break
        case 'move':
          operation.action = '移动了物品'
          // 尝试从内容中提取位置信息
          const moveMatch = activity.content.match(/从(.+?)移动到(.+?)$/)
          if (moveMatch) {
            operation.fromLocation = moveMatch[1]
            operation.toLocation = moveMatch[2]
          }
          break
        case 'login':
          operation.action = '登录了系统'
          break
        case 'logout':
          operation.action = '登出了系统'
          break
        default:
          operation.action = activity.title || '执行了操作'
      }
      
      return operation
    })
  }
  return []
})

// 格式化时间为"几小时前"的格式
const formatTimeAgo = (dateString) => {
  const now = new Date()
  const date = new Date(dateString)
  const diffMs = now - date
  const diffSec = Math.floor(diffMs / 1000)
  const diffMin = Math.floor(diffSec / 60)
  const diffHour = Math.floor(diffMin / 60)
  const diffDay = Math.floor(diffHour / 24)
  
  if (diffDay > 0) {
    return diffDay === 1 ? '昨天' : `${diffDay}天前`
  } else if (diffHour > 0) {
    return `${diffHour}小时前`
  } else if (diffMin > 0) {
    return `${diffMin}分钟前`
  } else {
    return '刚刚'
  }
}

// 获取物品数据
const recentItems = computed(() => {
  // 如果有数据，返回排序后的前4个物品
  if (itemsStore.items && itemsStore.items.length > 0) {
    return [...itemsStore.items]
      .sort((a, b) => new Date(b.createTime || b.purchaseDate) - new Date(a.createTime || a.purchaseDate))
      .slice(0, 4)
  }
  return []
})

// 获取用户第一个有权限的位置ID
const getFirstLocationId = () => {
  // 1. 首先尝试从URL查询参数获取位置ID
  const locationIdFromUrl = router.currentRoute.value.query.locationId;
  if (locationIdFromUrl) {
    console.log('getFirstLocationId: 从URL获取位置ID:', locationIdFromUrl, '类型:', typeof locationIdFromUrl);
    return locationIdFromUrl.toString();
  }
  
  // 2. 接着尝试从localStorage获取当前选择的位置ID
  const currentLocationId = localStorage.getItem('currentLocationId');
  if (currentLocationId) {
    console.log('getFirstLocationId: 从localStorage获取位置ID:', currentLocationId);
    return currentLocationId;
  }
  
  // 3. 如果上述都没有，再使用权限store中的第一个位置
  const userLocations = permissionStore.userLocationPermissions;
  
  if (!userLocations || Object.keys(userLocations).length === 0) {
    console.warn('getFirstLocationId: 用户没有位置权限');
    return null;
  }

  const firstLocationId = Object.keys(userLocations)[0];
  console.log('getFirstLocationId: 使用权限中的第一个位置:', firstLocationId);
  return firstLocationId;
}

// 获取所有消息数据
const fetchAllMessages = async () => {
  const locationId = getFirstLocationId();
  
  if (!locationId) {
    console.error('无法获取位置ID，无法加载消息数据');
    return false;
  }

  try {
    const response = await messagesApi.getMessages({
      locationId: locationId,
      getAllData: true // 获取所有数据
    });

    if (response && response.code === 200 && response.data) {
      // 如果服务器返回的是data.list数组
      if (Array.isArray(response.data.list)) {
        allMessages.value = response.data.list;
      } 
      // 如果服务器直接返回data作为数组
      else if (Array.isArray(response.data)) {
        allMessages.value = response.data;
      }
      // 如果返回的格式与上述都不匹配
      else {
        console.error('消息数据格式不符合预期:', response.data);
        allMessages.value = [];
      }
      
      // 适配后端字段名
      allMessages.value.forEach((msg) => {
        // 如果使用了snake_case而不是camelCase，进行转换
        if (msg.message_type && !msg.messageType) {
          msg.messageType = msg.message_type;
        }
        
        if (msg.sub_type && !msg.subType) {
          msg.subType = msg.sub_type;
        }
        
        if (msg.is_read !== undefined && msg.isRead === undefined) {
          msg.isRead = msg.is_read;
        }
        
        if (msg.create_time && !msg.createTime) {
          msg.createTime = msg.create_time;
        }
      });
      
      return true;
    } else {
      console.warn('获取消息数据失败:', response);
      return false;
    }
  } catch (error) {
    console.error('获取消息数据出错:', error);
    return false;
  }
}

onMounted(async () => {
  loading.value = true
  try {
    // 从URL查询参数获取locationId
    const locationIdFromUrl = router.currentRoute.value.query.locationId;
    console.log('URL参数中的位置ID:', locationIdFromUrl, '类型:', typeof locationIdFromUrl);
    
    if (locationIdFromUrl) {
      console.log('从URL查询参数获取位置ID:', locationIdFromUrl);
      // 保存到localStorage，确保是字符串格式
      localStorage.setItem('currentLocationId', locationIdFromUrl.toString());
      console.log('位置ID已保存到localStorage:', locationIdFromUrl.toString());
    } else {
      // 如果URL中没有位置ID，尝试从localStorage获取
      const savedLocationId = localStorage.getItem('currentLocationId');
      console.log('从localStorage获取到的位置ID:', savedLocationId);
      
      // 如果localStorage中有位置ID，更新到URL
      if (savedLocationId) {
        router.replace({
          path: router.currentRoute.value.path,
          query: { ...router.currentRoute.value.query, locationId: savedLocationId }
        });
        console.log('已从localStorage恢复位置ID到URL:', savedLocationId);
      }
    }
    
    // 确保用户已登录
    if (!userStore.isLoggedIn) {
      await userStore.getCurrentUser()
    }
    
    // 加载权限数据
    await permissionStore.loadUserLocationPermissions()
    
    // 加载消息数据（包含活动记录）
    await fetchAllMessages()
    
    // 加载物品数据
    await itemsStore.fetchItems()
  } catch (error) {
    console.error('加载数据失败:', error)
    // 确保仍然能显示一些内容
    if (itemsStore.items.length === 0 && typeof itemsStore.initMockData === 'function') {
      itemsStore.initMockData()
    }
  } finally {
    loading.value = false
  }
  
  // 监听系统颜色模式变化
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    isDarkMode.value = e.matches
  })
})

// 监听路由参数变化，当位置ID变化时重新加载数据
watch(
  () => router.currentRoute.value.query.locationId,
  async (newLocationId, oldLocationId) => {
    console.log('位置ID变化检测 [watch]:', oldLocationId, '->', newLocationId, '类型:', typeof newLocationId);
    
    if (newLocationId !== oldLocationId) {
      console.log('位置ID已变化:', oldLocationId, '->', newLocationId);
      
      // 保存新的位置ID到localStorage
      if (newLocationId) {
        localStorage.setItem('currentLocationId', newLocationId.toString());
        console.log('新位置ID已保存到localStorage:', newLocationId.toString());
      } else {
        localStorage.removeItem('currentLocationId');
        console.log('已从localStorage移除位置ID');
      }
      
      // 重新加载数据
      loading.value = true;
      try {
        // 加载消息数据（包含活动记录）
        await fetchAllMessages();
        
        // 加载物品数据
        await itemsStore.fetchItems();
        
        console.log('位置变更后数据已重新加载');
      } catch (error) {
        console.error('位置变更后重新加载数据失败:', error);
      } finally {
        loading.value = false;
      }
    }
  },
  { immediate: false } // 不需要立即执行，因为onMounted已经处理了初始数据加载
);

const navigateTo = (route, customQuery = {}) => {
  // 检查当前action是否有query参数
  const query = { ...customQuery };
  router.push({
    path: route,
    query
  })
}

const selectItem = (item) => {
  router.push(`/items/${item.id}`)
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

// 获取类别样式
const getItemCardClass = (category) => {
  const categoryMap = {
    '电子产品': 'card-electronics',
    '电器': 'card-appliance',
    '家具': 'card-furniture',
    '食品': 'card-kitchen',
    '厨房用品': 'card-kitchen',
    '衣物': 'card-default',
    '运动用品': 'card-default',
    '书籍': 'card-default',
    '文具': 'card-default',
    '玩具': 'card-default',
  };
  return categoryMap[category] || 'card-default';
}

// 获取分类图标
const getCategoryIconComponent = (category) => {
  const categoryMap = {
    '电子产品': Cpu,
    '电器': Cpu,
    '家具': OfficeBuilding,
    '食品': Food,
    '厨房用品': Food,
    '衣物': ShoppingBag,
    '运动用品': More,
  };
  return categoryMap[category] || More;
}
</script>

<template>
  <div class="apple-home fixed-height" :class="{ 'dark-mode': isDarkMode }">
    <!-- Updated Page Header -->
    <div class="user-header glass-effect">
      <div class="user-info">
        <el-avatar :icon="UserFilled" size="large" class="user-avatar"></el-avatar>
        <div class="greeting">
          <span class="welcome-text">你好,</span>
          <span class="user-name">{{ user.name }}!</span>
    </div>
          </div>
      <div class="quick-stats">
        <div class="stat-item" @click="navigateTo('/dashboard/items')">
          <el-icon :size="20"><Box /></el-icon>
          <span>{{ totalItems }} 件物品</span>
          </div>
        <div class="stat-item alert" @click="navigateTo('/dashboard/inventory')">
          <el-icon :size="20"><Bell /></el-icon>
          <span>{{ totalAlertsCount }} 项提醒</span>
        </div>
      </div>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="main-content-grid">
      <!-- 最近添加的物品 -->
      <transition name="slide-left">
        <div class="apple-content-card recent glass-effect hover-card">
          <div class="card-header">
            <h2>最近添加的物品</h2>
            <button class="apple-button apple-button-text button-float" @click="navigateTo('/dashboard/items')">
              查看全部
            </button>
          </div>
          
          <div v-if="loading" class="loading-container">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>
          
          <div v-else-if="recentItems.length === 0" class="empty-state">
            <div class="empty-icon">
              <el-icon><circle-plus /></el-icon>
            </div>
            <p>暂无最近添加的物品</p>
            <button class="apple-button apple-button-primary button-float" @click="navigateTo('/dashboard/items')">
              添加物品
            </button>
          </div>
          
          <!-- Updated recent items list using ItemList.vue style -->
          <div v-else class="recent-items-grid"> 
            <transition-group name="float-up">
              <div 
                v-for="(item, index) in recentItems"
                :key="item.id"
                class="item-card"
                :style="{ animationDelay: `${index * 0.05}s` }"
                @click="selectItem(item)"
              >
                <!-- 选择框位置（如需要） -->
                <div class="card-header">
                  <div class="card-title">{{ item.name }}</div>
                  <div class="card-quantity">
                    <span class="quantity-label">数量:</span>
                    <span class="quantity-value low">{{ item.quantity }}</span>
                </div>
                  </div>
                <div class="card-info">
                  <div class="info-item">
                    <el-icon><OfficeBuilding /></el-icon>
                    <span>{{ item.location || '-' }}</span>
                </div>
                  <div class="info-item">
                    <el-icon><ShoppingBag /></el-icon>
                    <span>{{ item.category || '-' }}</span>
                  </div>
                </div>
                <div class="card-footer">
                  <div class="card-date">购买于: {{ formatDate(item.purchaseDate) }}</div>
                  <div class="card-notes" :class="{'empty-notes': !item.notes}">{{ item.notes || '无备注' }}</div>
                </div>
              </div>
            </transition-group>
          </div>
        </div>
      </transition>
      
      <!-- 快速访问区域 -->
      <transition name="slide-right">
        <div class="apple-content-card quick-access glass-effect hover-card">
          <div class="card-header">
            <h2>快速操作</h2>
          </div>
          
          <div class="quick-access-grid">
            <div v-if="quickActions.length === 0" class="empty-state">
              <div class="empty-icon">
                <el-icon><connection /></el-icon>
              </div>
              <div class="empty-text">暂无快速操作</div>
            </div>
            <div v-else class="quick-access-actions">
              <transition-group name="float-up">
                <div 
                  v-for="(action, index) in quickActions" 
                  :key="action.id"
                  class="quick-access-item hover-card"
                  :style="{ animationDelay: `${index * 0.05}s` }"
                  @click="navigateTo(action.route, action.query || {})"
                >
                  <div class="quick-item-icon" :class="action.colorClass">
                    <el-icon><component :is="action.icon" /></el-icon>
                  </div>
                  <div class="quick-item-label">{{ action.label }}</div>
                </div>
              </transition-group>
            </div>
          </div>
        </div>
      </transition>
      
      <!-- 新的最近用户操作卡片 -->
      <transition name="slide-left">
        <div class="apple-content-card operations glass-effect hover-card">
          <div class="card-header">
            <h2>最近操作</h2>
            <button class="apple-button apple-button-text button-float" @click="navigateTo('/dashboard/notifications', { tab: 'recent' })">
              查看全部
            </button>
          </div>
          
          <div class="operations-list">
            <div v-if="recentOperations.length === 0" class="empty-state">
              <div class="empty-icon">
                <el-icon><clock /></el-icon>
              </div>
              <p>暂无最近操作记录</p>
            </div>
            
            <transition-group name="float-up" v-else>
                <div 
                v-for="(operation, index) in recentOperations" 
                :key="operation.id"
                class="operation-item"
                  :style="{ animationDelay: `${index * 0.05}s` }"
                >
                <div class="operation-user">
                  <el-avatar :size="32" class="user-avatar">{{ operation.username.charAt(0) }}</el-avatar>
                  <div class="operation-user-name">{{ operation.username }}</div>
                </div>
                
                <div class="operation-content">
                  <div class="operation-action">
                    <span class="action-text">{{ operation.action }}</span>
                    <span class="item-name">{{ operation.item }}</span>
            </div>
                  
                  <!-- 根据操作类型显示不同的详情 -->
                  <div class="operation-details" v-if="operation.action === '移动了物品'">
                    从 <span class="detail-value">{{ operation.fromLocation }}</span> 到 <span class="detail-value">{{ operation.toLocation }}</span>
                  </div>
                  
                  <div class="operation-details" v-else-if="operation.action === '更新了库存'">
                    数量从 <span class="detail-value">{{ operation.oldQuantity }}</span> 更新为 <span class="detail-value">{{ operation.newQuantity }}</span>
                  </div>
                  
                  <div class="operation-details" v-else-if="operation.action === '添加了备注'">
                    备注: <span class="detail-value">{{ operation.note }}</span>
                  </div>
                </div>
                
                <div class="operation-time">{{ operation.timeAgo }}</div>
              </div>
            </transition-group>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<style scoped>
.apple-home {
  /* padding: 16px; */ /* 移除内边距 */
  min-height: 100%;
  width: 100%;
  /* background-color: var(--apple-background-light); */ /* 移除背景色 */
  color: var(--apple-text-primary-light);
  transition: background-color var(--animation-speed-medium), 
              color var(--animation-speed-medium);
  overflow-x: hidden; /* 防止水平滚动 */
  max-width: 100vw; /* 限制最大宽度 */
}

/* 添加固定高度布局 */
.fixed-height {
  height: 100%; /* 改为100%以适应父容器 */
  overflow-y: auto; /* 只允许垂直滚动 */
  overflow-x: hidden; /* 禁止水平滚动 */
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* 特定移除暗黑模式下的背景色 */
.dark-mode.apple-home {
  /* background-color: var(--apple-background-dark); */ /* 移除背景色 */
  color: var(--apple-text-primary-dark);
}

/* Updated Header Styles */
.user-header {
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 18px 4px 18px 4px; /* 调整 padding，减少左右 */
  border-radius: 20px; /* 增大圆角 */
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8), rgba(245, 245, 250, 0.9));
  box-shadow: var(--shadow-sm);
  position: relative;
  overflow: hidden;
}

.dark-mode .user-header {
  background: linear-gradient(135deg, rgba(44, 44, 46, 0.8), rgba(58, 58, 60, 0.9));
  box-shadow: var(--shadow-sm-dark);
}

.user-header::before { /* Optional subtle shine effect */
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  transition: 0.8s;
}

.user-header:hover::before {
  left: 100%;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  background-color: var(--apple-blue);
  color: white;
  flex-shrink: 0;
}

.dark-mode .user-avatar {
  background-color: var(--apple-blue-dark);
}

.greeting {
  display: flex;
  flex-direction: column;
}

.welcome-text {
  font-size: 16px; /* 增大字体 */
  color: var(--apple-text-secondary-light);
}

.user-name {
  font-size: 20px; /* 增大字体 */
  font-weight: 600;
  color: var(--apple-text-primary-light);
}

.dark-mode .welcome-text {
  color: var(--apple-text-secondary-dark);
}

.dark-mode .user-name {
  color: var(--apple-text-primary-dark);
}

.quick-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px; /* 增大字体 */
  font-weight: 500;
  color: var(--apple-text-secondary-light);
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 12px; /* 增大圆角 */
  transition: background-color 0.2s ease;
}

.dark-mode .stat-item {
  color: var(--apple-text-secondary-dark);
}

.stat-item:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.dark-mode .stat-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.stat-item .el-icon {
  color: var(--apple-blue);
}

.dark-mode .stat-item .el-icon {
  color: var(--apple-blue-dark);
}

.stat-item.alert .el-icon {
  color: var(--apple-orange);
}

.dark-mode .stat-item.alert .el-icon {
  color: var(--apple-orange-dark);
}

/* 主要内容区域 */
.main-content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); /* 调整列宽最小值 */
  gap: var(--grid-gap, 20px);
  /* overflow: auto; */ /* 移除可能导致水平滚动的自动溢出 */
  overflow-y: auto; /* 只允许垂直方向的滚动 */
  overflow-x: hidden; /* 禁止水平方向的滚动 */
  flex: 1;
  width: 100%; /* 确保宽度遵循父容器 */
  box-sizing: border-box; /* 确保padding不会增加宽度 */
  /* 移除margin和padding */
}

.apple-content-card {
  max-height: calc(100vh - 180px);
  overflow-y: auto; /* 垂直方向允许滚动 */
  overflow-x: hidden; /* 水平方向禁止滚动 */
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 20px; /* 增大圆角 */
  box-shadow: var(--shadow-sm);
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all var(--animation-speed-medium) cubic-bezier(0.33, 1, 0.68, 1);
  position: relative;
  width: 100%; /* 确保宽度填满父容器 */
  box-sizing: border-box; /* 确保padding不会增加宽度 */
}

/* 添加空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 30px;
  height: 100%;
  min-height: 200px;
  width: 100%;
  box-sizing: border-box;
}

.empty-state .empty-icon {
  margin-bottom: 16px;
  font-size: 42px;
  color: var(--apple-text-tertiary-light);
  opacity: 0.6;
}

.dark-mode .empty-state .empty-icon {
  color: var(--apple-text-tertiary-dark);
}

.empty-state p {
  margin-bottom: 16px;
  color: var(--apple-text-secondary-light);
  font-size: 16px;
}

.dark-mode .empty-state p {
  color: var(--apple-text-secondary-dark);
}

.apple-content-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.8s;
  z-index: 1;
}

.apple-content-card:hover::before {
  left: 100%;
}

.dark-mode .apple-content-card {
  background-color: rgba(44, 44, 46, 0.8);
  box-shadow: var(--shadow-sm-dark);
}

.apple-content-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-md);
}

.dark-mode .apple-content-card:hover {
  box-shadow: var(--shadow-md-dark);
}

.card-header {
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--apple-border-light);
  z-index: 2;
}

.dark-mode .card-header {
  border-bottom: 1px solid var(--apple-border-dark);
}

.card-header h2 {
  font-size: 20px; /* 增大字体 */
  font-weight: 600;
  margin: 0;
  background: linear-gradient(90deg, var(--apple-text-primary-light), #555);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.dark-mode .card-header h2 {
  background: linear-gradient(90deg, var(--apple-text-primary-dark), #aaa);
  -webkit-background-clip: text;
}

/* 按钮样式 */
.apple-button {
  height: 36px;
  padding: 0 16px;
  border-radius: var(--button-border-radius);
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1);
  position: relative;
  overflow: hidden;
}

.apple-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.5s;
}

.apple-button:hover::before {
  left: 100%;
}

.apple-button-text {
  background-color: transparent;
  color: var(--apple-blue);
}

.apple-button-text:hover {
  text-shadow: 0 0 8px rgba(0, 122, 255, 0.3);
}

.dark-mode .apple-button-text {
  color: var(--apple-blue-dark);
}

.dark-mode .apple-button-text:hover {
  text-shadow: 0 0 8px rgba(10, 132, 255, 0.3);
}

.apple-button-primary {
  background: linear-gradient(135deg, var(--apple-blue), #0062cc);
  color: white;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
}

.apple-button-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.4);
}

.dark-mode .apple-button-primary {
  background: linear-gradient(135deg, var(--apple-blue-dark), #0A84FF);
  box-shadow: 0 2px 8px rgba(10, 132, 255, 0.3);
}

.dark-mode .apple-button-primary:hover {
  box-shadow: 0 4px 12px rgba(10, 132, 255, 0.4);
}

/* 最近添加的物品 */
.recent-items-grid {
  max-height: calc(100vh - 240px);
  width: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 16px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 0.8rem;
  box-sizing: border-box;
}

.recent-items-grid .item-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
  padding: 0.6rem;
  transition: all 0.2s ease;
  cursor: default;
  border: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
  display: flex;
  flex-direction: column;
}

.recent-items-grid .item-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transform: translateY(-3px);
}

.dark-mode .recent-items-grid .item-card {
  background-color: rgba(44, 44, 46, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.05);
}

.recent-items-grid .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  margin-left: 0;
  padding: 0;
  border-bottom: none;
  z-index: 1;
}

.recent-items-grid .card-title {
  font-weight: 600;
  color: #1d1d1f;
  font-size: 1rem;
  cursor: pointer;
  background: none;
  -webkit-text-fill-color: currentColor;
}

.dark-mode .recent-items-grid .card-title {
  color: #f5f5f7;
}

.recent-items-grid .card-quantity {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.recent-items-grid .quantity-label {
  font-size: 0.85rem;
  color: #86868b;
}

.recent-items-grid .quantity-value {
  font-weight: 600;
  font-size: 0.9rem;
  color: #1d1d1f;
}

.recent-items-grid .quantity-value.low {
  color: #ff3b30;
}

.recent-items-grid .card-info {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
  margin-bottom: 0.5rem;
  margin-left: 0;
}

.recent-items-grid .info-item {
  display: flex;
  align-items: center;
  color: #515154;
  font-size: 0.85rem;
}

.recent-items-grid .info-item .el-icon {
  margin-right: 0.4rem;
  font-size: 1rem;
  color: #86868b;
}

.recent-items-grid .card-footer {
  margin-top: auto;
  padding-top: 0.5rem;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  font-size: 0.8rem;
  color: #86868b;
  margin-left: 0;
}

.dark-mode .recent-items-grid .card-footer {
  border-top-color: rgba(255, 255, 255, 0.1);
}

.recent-items-grid .card-date {
  margin-bottom: 0.2rem;
}

.recent-items-grid .card-notes {
  font-style: italic;
}

.recent-items-grid .card-notes.empty-notes {
  color: #c7c7cc;
  font-style: normal;
}

/* 快速访问卡片 */
.quick-access-grid {
  padding: 24px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 16px;
}

.quick-access-item {
  flex: 1 0 calc(33.333% - 10px); /* 使用flex替代固定宽度 */
  min-width: 90px;
  min-height: 90px;
  max-width: 100%; /* 确保不超过父容器 */
  box-sizing: border-box;
  /* 恢复被删除的样式 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px;
  border-radius: 18px; /* 增大圆角 */
  background-color: var(--el-bg-color);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
  animation: float-in 0.5s ease forwards;
}

.quick-access-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.quick-item-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 10px;
  margin-bottom: 8px;
  color: white;
}

.quick-item-label {
  font-size: 16px; /* 增大字体 */
  font-weight: 500;
  color: var(--el-text-color-primary);
  text-align: center;
}

/* 动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .apple-home {
    /* padding: 16px; */
  }
  
  .home-header {
    padding: 20px;
    margin-bottom: 24px;
  }
  
  .page-title {
    font-size: 28px;
  }
  
  .main-content-grid {
    grid-template-columns: 1fr;
  }
  
  .apple-content-card, .card-header, .location-stats {
    padding: 16px;
  }
  
  .quick-access-grid {
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); /* 使用auto-fit和minmax适应各种屏幕 */
  }
  
  .quick-access-item {
    width: 100%; /* 在小屏幕上确保宽度100% */
    min-width: auto; /* 移除最小宽度限制 */
  }
}

.quick-access-actions {
  display: flex;
  flex-wrap: wrap; /* 确保内容换行 */
  gap: 15px;
  width: 100%;
  box-sizing: border-box;
}

.quick-access-item {
  flex: 1 0 calc(33.333% - 10px); /* 使用flex替代固定宽度 */
  min-width: 90px;
  min-height: 90px;
  max-width: 100%; /* 确保不超过父容器 */
  box-sizing: border-box;
}

.bg-green { background-color: #42b883; }
.bg-blue { background-color: #3498db; }
.bg-orange { background-color: #e67e22; }
.bg-purple { background-color: #9b59b6; }
.bg-indigo { background-color: #5D5CDE; }
.bg-cyan { background-color: #1abc9c; }
.bg-brown { background-color: #8B5A2B; }
.bg-red { background-color: #e74c3c; }
.bg-pink { background-color: #e84393; }
.bg-gray { background-color: #7f8c8d; }

.recent-item-category-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 10px;
  margin-right: 12px;
  color: white;
}

.separator {
  margin: 0 5px;
  color: var(--el-text-color-secondary);
}

.quantity-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 22px;
  height: 22px;
  padding: 0 6px;
  border-radius: 11px;
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  font-size: 12px;
  font-weight: 600;
}

@keyframes float-in {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.float-up-enter-active,
.float-up-leave-active {
  transition: all 0.3s;
}

.float-up-enter-from,
.float-up-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

@media (prefers-color-scheme: dark) {
  .quick-access-item,
  .recent-item {
    background-color: var(--el-bg-color-overlay);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }
  
  .quick-access-item:hover,
  .recent-item:hover {
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  }
  
  .quantity-badge {
    background-color: rgba(64, 158, 255, 0.2);
  }
}

/* 最近操作卡片样式 */
.operations-list {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow-y: auto;
  max-height: calc(100vh - 240px);
}

.operation-item {
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  transition: all 0.2s ease;
  border: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.dark-mode .operation-item {
  background-color: rgba(44, 44, 46, 0.7);
  border: 1px solid rgba(255, 255, 255, 0.05);
}

.operation-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
}

.operation-user {
  display: flex;
  align-items: center;
  gap: 8px;
}

.operation-user-name {
  font-weight: 600;
  font-size: 0.95rem;
  color: var(--apple-text-primary-light);
}

.dark-mode .operation-user-name {
  color: var(--apple-text-primary-dark);
}

.operation-content {
  margin-left: 40px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.operation-action {
  font-size: 0.9rem;
  color: var(--apple-text-primary-light);
}

.dark-mode .operation-action {
  color: var(--apple-text-primary-dark);
}

.item-name {
  font-weight: 500;
  color: var(--apple-blue);
}

.dark-mode .item-name {
  color: var(--apple-blue-dark);
}

.operation-details {
  font-size: 0.85rem;
  color: var(--apple-text-secondary-light);
}

.dark-mode .operation-details {
  color: var(--apple-text-secondary-dark);
}

.detail-value {
  font-weight: 500;
  color: var(--apple-text-primary-light);
}

.dark-mode .detail-value {
  color: var(--apple-text-primary-dark);
}

.operation-time {
  margin-left: 40px;
  font-size: 0.8rem;
  color: var(--apple-text-tertiary-light);
}

.dark-mode .operation-time {
  color: var(--apple-text-tertiary-dark);
}
</style> 